<template>
  <div class="create-table-config">
    <el-form ref="formDataRef" :model="dataForm" :rules="formRules" style="margin-bottom: 32px;" label-position="right" label-width="110px">
      <el-form-item label="图表名称" prop="name" class="name">
        <el-input
          v-model.trim="dataForm.name"
          maxlength="20"
          class="width240"
          size="small"
          placeholder="请填写报表名称"
          name="name"
          type="text"/>
      </el-form-item>
    </el-form>
    <Title title="数据配置" style="margin-bottom: 16px" />
    <div class="form-item">
      <div class="label">是否作为数据源</div>
      <div class="flex-center" style="height: 30px;">
        <el-switch
          v-model="dataForm.hasDataSource"
          class="fb-switch"
        />
      </div>
    </div>
    <SelectTableField v-model="dataForm" :system-condition-options="systemConditionOptions" @changeData="tableFieldChangeData" />
    <div class="form-item">
      <div class="label">数据筛选</div>
      <FilterSelectModule
        v-if="!filterFlag"
        :has-data-source="dataForm.hasDataSource"
        v-model="dataForm.chartFilter[0].system"
        :unit-params="{
          field: 'sourceName',
        }"
        :math-options="mathOptions"
        :field-chidren-list="filterFields()"
        key-name="uniqueId" />
    </div>
    <div class="form-item">
      <div class="label">添加汇总行</div>
      <el-switch
        v-model="hasCollectColumn"
        :active-value="1"
        :inactive-value="0"
        style="margin-top: 7px;margin-right:13px;"
        class="fb-switch"
      />
      <TableCollectColumn v-if="hasCollectColumn" ref="collectColumnRef" :field-list="allFields" class="table-scroll-auto" />
    </div>
    <div class="form-item">
      <div class="label">编辑列宽度</div>
      <el-switch
        v-model="hasDiyWidth"
        :active-value="1"
        :inactive-value="0"
        style="margin-top: 7px;margin-right:13px;"
        class="fb-switch"
      />
      <SetTableWidth v-if="hasDiyWidth && allFields.length" ref="setTableWidthRef" v-model="diyTableWidth" :field-list="allFields" />
    </div>
    <div class="form-item">
      <div class="label">排序</div>
      <div class="flex-center">
        <div class="flex-center" style="height: 30px;margin-right: 13px;">
          <el-switch v-model="dataForm.isOrder" class="fb-switch" />
        </div>
        <div v-if="dataForm.isOrder" class="select-sort">
          <!-- 当前选择的字段 -->
          <el-select
            v-model="dataForm.sortFieldName"
            size="small"
            placeholder="字段"
            class="wiidth120"
            popper-class="global-select-down"
            clearable
            name="sortField">
            <el-option
              v-for="item in allFields"
              :key="item.uniqueId"
              :label="item.name+`${item.sourceName?`（${item.sourceName}）`:''}`"
              :value="item.uniqueId" />
          </el-select>
          <el-select
            v-model="dataForm.sortType"
            placeholder="展示排序"
            size="small"
            class="wiidth120"
            popper-class="global-select-down"
            name="sortType">
            <el-option
              v-for="item in sortOpt"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
          <el-input
            v-model="dataForm.showNums"
            type="number"
            oninput="if(value || value === 0) {if(value>999999999)value=999999999;if(value<1)value=1;}"
            class="input-align-left"
            size="small"
            placeholder="展示数量" />
          <el-select
            v-model="dataForm.sortShowType"
            size="small"
            placeholder="数据排序"
            class="wiidth120"
            popper-class="global-select-down"
            name="sortShowType">
            <el-option
              v-for="item in sortShowTypeOpt"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </div>
      </div>
    </div>
    <div class="form-item">
      <div class="label">
        <div class="flex-center">
          设置拆分字段
          <tipIcon content="可对数据维度进行字段内容拆分。请输入拆分字段的标识。" />
        </div>
      </div>
      <div class="flex-center" style="height: 30px;">
        <el-switch
          v-model="dataForm.isSplitChunk"
          class="fb-switch mr10"
        />
        <el-input
          v-if="dataForm.isSplitChunk"
          v-model="dataForm.chunkSeparator"
          :maxlength="10"
          type="text"
          class="input-align-left"
          size="small"
          placeholder="请输入拆分标识" />
      </div>
    </div>
    <div class="form-item">
      <div class="label">定时更新</div>
      <div class="flex-center" style="height: 30px;">
        <el-switch
          v-model="dataForm.isUpdateRegularly"
          class="fb-switch"
        />
        <el-select
          v-if="dataForm.isUpdateRegularly"
          v-model="dataForm.updateRegularlyType"
          placeholder="请选择"
          size="small"
          class="select-updateRegularlyType"
          popper-class="global-select-down"
          name="sortType">
          <el-option
            v-for="item in updateRegularlyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </div>
    </div>
    <div class="form-item">
      <div class="label">是否展示</div>
      <div class="flex-center" style="height: 30px;">
        <el-switch
          v-model="dataForm.isShow"
          class="fb-switch"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Title from '@/components/Title';
import SelectTableField from './selectTableField';
import { getDataTable } from '@/api/reportManage'; // getDataTable
import FilterSelectModule from '@/components/ReportManage/filterSelectModule';
import TableCollectColumn from '@/components/ReportManage/chartCreate/module/tableCollectColumn';
import SetTableWidth from '@/components/ReportManage/chartCreate/module/SetTableWidth';
import { updateRegularlyOptions } from '@/components/ReportManage/chartCreate/module/selectData.js';

export default {
  components: { Title, SelectTableField, FilterSelectModule, TableCollectColumn, SetTableWidth },
  model: {
    prop: 'dataForm',
    event: 'changeData'
  },
  props: {
    dataForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      updateRegularlyOptions,
      systemConditionOptions: [],
      mathOptions: [],
      callback: null,
      hasCollectColumn: 0,
      hasDiyWidth: 0,
      sortOpt: [{ id: 1, name: '正序' }, { id: 2, name: '倒序' }],
      sortShowTypeOpt: [{ id: 1, name: '升序' }, { id: 2, name: '降序' }],
      diyTableWidth: {},
      filterFlag: false,
      formRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写报表名称' }]
      }
    };
  },
  computed: {
    allFields() {
      this.dataForm.selectField.forEach(i => {
        i.name = i.fieldName;
      });
      // return this.dataForm.selectField.filter(i => i.columnName && i.fieldName);
      return this.dataForm.selectField.filter(i => i.columnName);
    }
  },
  created() {
    this.chartId = this.$route.params.id || null;
    this.getOptions();
  },
  methods: {
    async setDefault(data) {
      await this.$nextTick();
      if (data.collectColumn && data.collectColumn.field && data.collectColumn.field.length) {
        this.hasCollectColumn = 1;
        this.$nextTick(() => {
          if (this.$refs.collectColumnRef) this.$refs.collectColumnRef.setDefault(data);
        });
      }
      try {
        const styleConfig = this.dataForm.styleConfig || {};
        const setting = styleConfig && typeof styleConfig === 'string' ? JSON.parse(styleConfig) : styleConfig;
        const isEmpty = setting.diyTableWidth ? Object.keys(setting.diyTableWidth).length === 0 : true;
        this.diyTableWidth = isEmpty ? {} : setting.diyTableWidth;
        this.hasDiyWidth = isEmpty ? 0 : 1;
      } catch (error) {
        this.diyTableWidth = {};
      }

      this.callback = () => {
        const systemConditionOptions = this.systemConditionOptions;
        this.dataForm.selectField.forEach(i => {
          const dataSheetItem = systemConditionOptions.find(j => j.id === i.sourceId);
          if (dataSheetItem) {
            dataSheetItem.field.forEach(j => {
              j.sourceId = i.sourceId;
            });
            i.fieldChidrenList = dataSheetItem.field;
          } else {
            i.fieldChidrenList = [];
          }
          // 公式字段
          if (i.fieldType === 1) {
            if (i.formulaOrigin && i.formulaOrigin !== '' && typeof i.formulaOrigin === 'string') {
              i.formulaOrigin = JSON.parse(i.formulaOrigin);
            }
            // 关联变量对象的指针地址
            if (i.formulaOrigin && i.formulaOrigin.length) {
              for (let j = 0; j < i.formulaOrigin.length; j++) {
                this.dataForm.selectField.forEach(k => {
                  if (!k.fieldType && i.formulaOrigin[j].type === 'var' && k.columnName === i.formulaOrigin[j].columnName) {
                    k.type = 'var';
                    i.formulaOrigin[j] = k;
                  }
                });
              }
            }
          } else {
            const fieldItem = i.fieldChidrenList.find(j => j.name === i.fieldName);
            if (fieldItem) i.optionsType = fieldItem.optionsType;
          }
        });
        this.changeData();
        this.callback = null;
      };
      if (this.systemConditionOptions.length) {
        this.callback();
      }
    },
    changeData() {
      this.$emit('changeData', this.dataForm);
    },
    tableFieldChangeData() {
      this.changeData();
      this.filterFlag = true;
      this.$nextTick(() => {
        this.filterFlag = false;
      });
      // 选取字段的数据改变后，需要判断数据筛选是否有使用该数字表的字段，有使用则清空
      if (this.dataForm.chartFilter && this.dataForm.chartFilter.length && this.dataForm.chartFilter[0].system) {
        this.dataForm.chartFilter[0].system.forEach((i, index) => {
          const hasData = this.dataForm.selectField.some(j => {
            return j.sourceId === i.top;
          });
          if (!hasData) {
            const initData = {
              top: null,
              type: 0, // 0:时间筛选 1:条件筛选 2:文本筛选
              begin: '', end: '', field: '', optionsType: '',
              monthOnMonth: false, yearOnYear: false,
              operation: '', // 操作，=,>,<,>=,<= 和 包含，不包含，首字
              value: '', conditionValue: '', timeRangeType: '',
              reportField: '', // 【v2.8.9】报表字段（手动输入）,当选择的字段为报表字段时才生效
              isOpenFilter: false, // 是否开启筛选
              defaultMath: '', // 默认筛选的运算条件
              defaultValue: '', // 默认筛选条件
              defaultNumberRange: [], // 默认筛选条件
              defaultTimeRange: [] // 默认筛选条件
            };
            this.$set(this.dataForm.chartFilter[0].system, index, initData);
          }
        });
      }
      // 选取字段的数据改变后，判断排序字段还存不存在
      if (this.dataForm.selectField && this.dataForm.selectField.length) {
        const hasField = this.dataForm.selectField.some(i => {
          return i.uniqueId === this.dataForm.sortFieldName;
        });
        if (!hasField) {
          this.$set(this.dataForm, 'sortFieldName', '');
        }
      } else {
        this.$set(this.dataForm, 'sortFieldName', '');
      }
    },
    filterFields() {
      const list = this.dataForm.selectField;
      let fieldList = [];
      list.forEach(i => {
        if (i.fieldChidrenList && i.fieldChidrenList.length) {
          fieldList = fieldList.concat(i.fieldChidrenList || []);
        }
      });
      fieldList = _.unionBy(fieldList, 'uniqueId');
      return fieldList;
    },
    getOptions() {
      getDataTable({ chartId: this.chartId }).then(res => {
        if (res.data) {
          res.data.condition.forEach(i => {
            if (i.field) {
              i.field.forEach(j => {
                j.sourceId = i.id;
                j.sourceName = i.name;
                if (!j.uniqueId) {
                  j.uniqueId = `${j.name}#${j.sourceId}`;
                }
              });
            }
          });
          this.systemConditionOptions = res.data.condition;
          this.mathOptions = res.data.mathOptions;
          if (this.callback) {
            this.callback();
          }
        }
      });
    },
    handelSetTableWidth() {
      if (!this.hasDiyWidth) return null;
      const allFieldsColumn = this.allFields.map(i => i.columnName);
      const diyTableWidth = this.diyTableWidth;
      const obj = {};
      for (const key in diyTableWidth) {
        if (allFieldsColumn.includes(key) && (diyTableWidth[key] || diyTableWidth[key] === 0)) {
          obj[key] = diyTableWidth[key];
        }
      }
      return obj;
    },
    handelParams() {
      const diyTableWidth = this.handelSetTableWidth();
      if (this.hasCollectColumn) {
        const collectColumnRef = this.$refs.collectColumnRef;
        if (collectColumnRef) {
          const collectColumnData = collectColumnRef.getParams();
          if (collectColumnData.error) {
            this.$message.error(collectColumnData.error);
            return;
          }
          this.dataForm.collectColumn = collectColumnData.data;
        }
      } else {
        this.dataForm.collectColumn = {};
      }
      this.changeData();
      return diyTableWidth;
    },
    validate() {
      // 提供给父组件来验证完整性
      return new Promise((resolve, reject) => {
        this.$refs.formDataRef.validate(valid => {
          if (valid) {
            resolve(valid);
          } else {
            reject();
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-table-config {
  margin-top: 16px;
  .one-cell {
    display: flex;
  }
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
  }
}
.form-item {
  display: flex;
  margin-bottom: 24px;
  .label {
    flex-shrink: 0;
    text-align: right;
    font-size: 14px;
    color: #666;
    margin-right: 10px;
    width: 100px;
    line-height: 32px;
  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.table-scroll-auto {
  @include scrollBar(auto, hidden, 6px);
}
.select-updateRegularlyType {
  width: 120px;
  margin-left: 10px;
  .el-input__inner {
    width: 120px !important;
  }
}
.flex-center {
  display: flex;
  align-items: center;
}
.input-align-left {
  width: 130px;
  &::v-deep {
    .el-input__inner {
      text-align: left;
      width: 130px;
    }
  }
}
.wiidth120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
</style>
